package fr.labri.macchiato.framework.business.sparql;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.labri.macchiato.framework.business.encoder.Encoders;
import fr.labri.macchiato.framework.business.finder.BusinessEntityFinder;
import fr.labri.macchiato.framework.business.finder.Callback;
import fr.labri.macchiato.framework.business.model.businessEntity.BusinessEntity;
import fr.labri.macchiato.framework.technical.encoder.Encoder;
import fr.labri.macchiato.framework.technical.queryLauncher.RpcQueryLauncher;
import fr.labri.macchiato.framework.technical.queryLauncher.RpcQueryLauncherAsync;
import fr.labri.macchiato.framework.util.FrameworkException;

/**
 * Class that sends the SPARQL queries in order to retrieve information on
 * business entities.
 * 
 * @author Michelle AVOMO
 * 
 */
public class SparqlBusinessEntityFinder implements BusinessEntityFinder {

	private RpcQueryLauncherAsync queryLauncher;
	String getQuery;

	/**
	 * Default constructor
	 */
	public SparqlBusinessEntityFinder() {
		queryLauncher = GWT.create(RpcQueryLauncher.class);
	}

	/************************************** UNIMPLEMENTED METHODS *********************************************************/
	
	/**
	 * Fetch companies' infos details in the db 
	 * @param callback
	 *            : list of info details such as page,logo and legalName
	 */
	@Override
	public void getAllInfosOfEntities(
			final Callback<List<BusinessEntity>> callback) {
		getQuery = QueryFactory.getInstance().retrieveAllInfosOnEntities();

		queryLauncher.launchQueryForJSON(getQuery, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
				throw new FrameworkException(
						"Echec lors de la récuperation du nom + page + logo des groupes");
			}

			@Override
			public void onSuccess(String result) {
				List<BusinessEntity> details = getBusinessEntityEncoder()
						.decodeSparqlResult(result);
				callback.onCallback(details);

			}

		});

	}
	/***************************************** PRIVATE METHODS ************************************************/

	/**
	 * Retrieve the list of business entities from the database and encode them
	 * in the json format
	 * 
	 */
	private Encoder<BusinessEntity> getBusinessEntityEncoder() {
		return Encoders.getInstance().getBusinessEntityEncoder();
	}

}
